<template>
  <div class="login">
    <div class="container">
      <img src="../assets/avatar.jpg" alt="" class="avatar" />
      <el-form
        :model="userForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user-solid"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="userForm.password"
            placeholder="请输入密码"
            prefix-icon="el-icon-key"
          ></el-input>
          <el-button type="primary" class="login_btn" @click="login"
            >登陆</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { userlogin } from "@/apis/user.js";
export default {
  data() {
    return {
      userForm: {
        username: "13800138000",
        password: "123",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名！", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码！", trigger: "blur" },
          { min: 3, max: 16, message: "情输入3-16位密码", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    login() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          try {
            let res = await userlogin(this.userForm);
            console.log("登录", res);
            if (res.data.message == "登录成功") {
              this.$message({
                message: "恭喜登录成功！",
                type: "success",
              });
              this.$router.push({ path: "/index" });
              localStorage.setItem("hmtoutiao_back_token", res.data.data.token);
            }
          } catch {
            this.$message({
              message: "账户名或密码输入有误！",
              type: "error",
            });
          }
        } else {
          this.$message({
            message: "请正确输入账户名和密码！",
            type: "warning",
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 100%;
  background-color: #2f4050;
  position: fixed;
  .container {
    width: 400px;
    margin: 200px auto;
    background-color: #fff;
    padding: 20px 40px;
    .login_btn {
      width: 100%;
      margin-top: 20px;
    }
    .avatar {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      position: relative;
      top: 0;
      left: 50%;
      margin-left: -60px;
      margin-top: -60px;
    }
  }
}
</style>